package com.clz.appdesign.myapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.SuperKotlin.pictureviewer.ImagePagerActivity;
import com.SuperKotlin.pictureviewer.PictureConfig;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clz.appdesign.Notification.ProgressBarActivity;
import com.clz.appdesign.appdependence.net.RetrofitFactory;
import com.clz.appdesign.appdependence.net.RxSchedulers;
import com.clz.appdesign.appdependence.net.base.BaseObserver;
import com.clz.appdesign.audio_video.AudioVideoPrimaryActivity;
import com.clz.appdesign.basic_study.ContentProviderActivity;
import com.clz.appdesign.chart.ChartActivity;
import com.clz.appdesign.databinding.DataBindingActivity;
import com.clz.appdesign.mvvm.ImageSeeActivity;
import com.clz.appdesign.myapp.anim.ObjectAnimatiorActivity;
import com.clz.appdesign.myapp.download.DownloadActivity;
import com.clz.appdesign.myapp.ijkplayer.IjkPlayerActivity;
import com.clz.appdesign.myapp.kotlin.KotlinActivity;
import com.clz.appdesign.myapp.media.VideoActivity;
import com.clz.appdesign.myapp.notification.NotificationActivity;
import com.clz.appdesign.myapp.utils.DensityUtil;
import com.clz.appdesign.myapp.view.CustomViewActivity;
import com.clz.appdesign.myapp.webview.CommonWebActivity;
import com.clz.appdesign.ndk.JniActivity;
import com.clz.appdesign.net_kotlin.RetrofitKotlinActivity;
import com.clz.appdesign.socket.SimpleClientActivity;
import com.clz.appdesign.viewpager.ViewPagerActivity;
import com.liulishuo.okdownload.DownloadListener;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @autor chenliangzhi
 * @date 2018/1/25
 * @desc
 */
public class MainActivity extends RxAppCompatActivity {
    @BindView(R.id.ll_root)
    LinearLayout mLlRoot;
    private List<String> imageList = new ArrayList<>();
    private RxPermissions mRxPermissions = null;
    private static final String[] PERMISSIONS_NEED = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        LogUtils.d("哈啊");
        imageList.add("http://b.hiphotos.baidu.com/image/pic/item/aec379310a55b31932bea15a4fa98226cffc175d.jpg");
        imageList.add("http://d.hiphotos.baidu.com/image/pic/item/8601a18b87d6277fcdb9b01d24381f30e924fc68.jpg");
        imageList.add("http://d.hiphotos.baidu.com/image/h%3D300/sign=b267c1142d3fb80e13d167d706d02ffb/4034970a304e251f264429ddab86c9177f3e5360.jpg");
        imageList.add("http://a.hiphotos.baidu.com/image/h%3D300/sign=64b8dfdd77cb0a469a228d395b63f63e/7dd98d1001e939014974b01977ec54e736d196a6.jpg");
        imageList.add("http://d.hiphotos.baidu.com/image/pic/item/8601a18b87d6277fcdb9b01d24381f30e924fc68.jpg");
        Map<String, Object> params = new HashMap<>();
        params.put("cityname", "北京");
        params.put("format", 2);
        params.put("key", "2896f8e1e327aa8f50cfa65bd2746de9");
        testRetrofit(params);
        mRxPermissions = new RxPermissions(this);
        getPermission();
    }

    private void getPermission() {
        mRxPermissions.request(PERMISSIONS_NEED)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            ToastUtils.showShort("权限申请通过");
                        } else {
                            getPermission();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void testRetrofit(Map<String, Object> params) {
        RetrofitFactory.getInstence().createService(APIFunction2.class).getBaidu1(params)
                .compose(this.bindToLifecycle())
                .compose(RxSchedulers.io_main())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<WeatherBean>() {
                    @Override
                    protected void onSucceed(WeatherBean weatherBean) throws Exception {
//                        ToastUtils.showLong(weatherBean.getSk().toString());
//                        LogUtils.iTag("HHA",weatherBean.getSk().toString());
                    }

                    @Override
                    protected void onCodeError(int error_code, String reason) throws Exception {
                        super.onCodeError(error_code, reason);
//                        Log.i("HHA",reason);
                    }
                });
    }


    @OnClick({R.id.btn_mvvm,R.id.btn_ok_download, R.id.btn_retrofit_kotlin, R.id.btn_router, R.id.btn_audio1, R.id.progressbar, R.id.btn_chart, R.id.btn_jni, R.id.btn_socket, R.id.btn_data_binding, R.id.btn_custom_view, R.id.btn_new_control, R.id.btn_object_anim, R.id.btn_webview, R.id.btn_notification, R.id.btn_ijkplayer, R.id.btn_video, R.id.btn_download, R.id.btn_kotlin, R.id.btn_dagger2, R.id.btn_vp, R.id.btn_rec_image, R.id.btn_rx_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_mvvm:
                startActivity(new Intent(this, ImageSeeActivity.class));
            case R.id.btn_ok_download:
                testOkDownLoad();
                break;
            case R.id.btn_retrofit_kotlin:
                startActivity(new Intent(this, RetrofitKotlinActivity.class));
                break;
            case R.id.btn_router:
                ARouter.getInstance().build("/com/ArouterActivity")
                        .withString("test", "哈哈")
                        .navigation();
                break;
            case R.id.btn_audio1:
                startActivity(new Intent(this, AudioVideoPrimaryActivity.class));
                break;
            case R.id.progressbar:
                startActivity(new Intent(this, ProgressBarActivity.class));
                break;
            case R.id.btn_chart:
                startActivity(new Intent(this, ChartActivity.class));
                break;
            case R.id.btn_jni:
                startActivity(new Intent(this, JniActivity.class));
                break;
            case R.id.btn_socket:
                startActivity(new Intent(this, SimpleClientActivity.class));
                break;
            case R.id.btn_data_binding:
                startActivity(new Intent(this, DataBindingActivity.class));
                break;
            case R.id.btn_custom_view:
                startActivity(new Intent(this, CustomViewActivity.class));
                break;
            case R.id.btn_new_control:
                startActivity(new Intent(this, BottomNavigationActivity.class));
                break;
            case R.id.btn_object_anim:
                startActivity(new Intent(this, ObjectAnimatiorActivity.class));
                break;
            case R.id.btn_webview:
                final Intent intent = new Intent(this, CommonWebActivity.class);
                intent.putExtra("url", "https://www.baidu.com");
                startActivity(intent);
                break;
            case R.id.btn_notification:
                startActivity(new Intent(this, NotificationActivity.class));
                break;
            case R.id.btn_kotlin:
                startActivity(new Intent(this, KotlinActivity.class));
                break;
            case R.id.btn_dagger2:
                startActivity(new Intent(this, ContentProviderActivity.class));
                break;
            case R.id.btn_vp:
                startActivity(new Intent(this, ViewPagerActivity.class));
                break;
            case R.id.btn_rec_image:
                PictureConfig config = new PictureConfig.Builder()
                        .setListData((ArrayList<String>) imageList)    //图片数据List<String> list
                        .setPosition(4)    //图片下标（从第position张图片开始浏览）
                        .setDownloadPath("pictureviewer")    //图片下载文件夹地址
                        .setIsShowNumber(true)//是否显示数字下标
                        .needDownload(true)    //是否支持图片下载
                        .setPlacrHolder(R.mipmap.ic_launcher)    //占位符图片（图片加载完成前显示的资源图片，来源drawable或者mipmap）
                        .build();
                ImagePagerActivity.startActivity(this, config);
                break;
            case R.id.btn_rx_image:
                startActivity(new Intent(this, RxImageActivity.class));
                break;
            case R.id.btn_download:
                startActivity(new Intent(this, DownloadActivity.class));
                break;
            case R.id.btn_video:
                startActivity(new Intent(this, VideoActivity.class));
                break;
            case R.id.btn_ijkplayer:
                startActivity(new Intent(this, IjkPlayerActivity.class));
                break;
            default:
                break;
        }
    }

    private void testOkDownLoad() {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                + "Test";
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        } else {
            file.mkdirs();
        }
        String fileName = "test.apk";
        String downLoadUrl = "https://m.youjuke.com/download/BuildMaterialsReceipt.apk";
        DownloadTask downloadTask = new DownloadTask.Builder(downLoadUrl, filePath, fileName)
                // the minimal interval millisecond for callback progress
                .setMinIntervalMillisCallbackProcess(30)
                // do re-download even if the task has already been completed in the past.
                .setPassIfAlreadyCompleted(false)
                .build();
        final DownloadListener listener = new DownloadListener4WithSpeed() {
            long totalLength;
            ProgressBar progressBar=new ProgressBar(MainActivity.this,null,
            android.R.attr.progressBarStyleHorizontal);

            @SuppressLint("WrongConstant")
            @Override
            public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                totalLength = info.getTotalLength();
                LogUtils.iTag("download2", totalLength);
                final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.height= (int) DensityUtil.px2dp(MainActivity.this,20.0f);
                progressBar.setLayoutParams(layoutParams);
                mLlRoot.addView(progressBar);
            }

            @Override
            public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {

            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                //LogUtils.iTag("download2",  currentOffset);
                final int progress = (int) (((currentOffset * 1.0) / totalLength) * 100);
                progressBar.setProgress(progress);
                LogUtils.iTag("download2", progress);
            }

            @Override
            public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {

            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                progressBar.setVisibility(View.GONE);
                ToastUtils.showLong("下载完成");
            }

            @Override
            public void taskStart(@NonNull DownloadTask task) {

            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {

            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {

            }
        };
        downloadTask.enqueue(listener);
        //downloadTask.execute(listener);
    }
}
